//
//  MLRegisterContainerViewController.m
//  MeshLamp
//
//  Created by new on 2017/11/6.
//  Copyright © 2017年 make. All rights reserved.
//

#import "MLCircleInfoMainPageViewController.h"
//#import "MLSignUpViewController.h"
#import "MHMomentViewController.h"
#import "MHMomentViewModel.h"
#import "MHCircleMainPageBottonView.h"
#import "MLCircleInfoMainPageViewModel.h"
#import "MHCircleInfoHeader.h"
#import "MHSuccessCreateCircleView.h"
#import "UIView+Shake.h"
#import "MHWebViewModel.h"
#import <TXLiteAVSDK_UGC/TXUGCBase.h>
#import "SharePopView.h"
#import "MHDetailLocationViewModel.h"
#import "MHPhotoManager.h"

@interface MLCircleInfoMainPageViewController ()
@property(nonatomic, strong) MHCircleMainPageBottonView *circleInfoBottom;
@property(nonatomic, strong) MLCircleInfoMainPageViewModel *viewModel;
@property (nonatomic, strong) MHCircleInfoHeader *header;
@property(nonatomic, strong) UIButton *activityButton;
@property(nonatomic, assign) BOOL inThisPage;
@property(nonatomic, assign) BOOL isExpand;
@property(nonatomic, strong) UIButton *hoverBtn;


@end

@implementation MLCircleInfoMainPageViewController
@dynamic viewModel;

- (instancetype)initWithViewModel:(MLCircleInfoMainPageViewModel *)viewModel {
    self = [super initWithViewModel:viewModel];
    
    if (self) {
        
        
        MHMomentViewModel  *topic = [[MHMomentViewModel alloc] initWithServices:self.viewModel.services params:@{MHViewModelTitleKey:@"主题",MHViewModelUtilKey:@(0), MHViewModelIDKey: @(self.viewModel.circielId) }];
        MHMomentViewModel  *ask = [[MHMomentViewModel alloc] initWithServices:self.viewModel.services params:@{MHViewModelTitleKey:@"问答",MHViewModelUtilKey:@(2),MHViewModelIDKey: @(self.viewModel.circielId)}];
        MHMomentViewModel  *cream = [[MHMomentViewModel alloc] initWithServices:self.viewModel.services params:@{MHViewModelTitleKey:@"精华",MHViewModelUtilKey:@(1),MHViewModelIDKey: @(self.viewModel.circielId)}];
        topic.isTheme = true;
        ask.isTheme = true;
        cream.isTheme = true;
        MHMomentViewController *topicMoment = [[MHMomentViewController alloc] initWithViewModel:topic];
        
//        MHMomentViewController *askMoment = [[MHMomentViewController alloc] initWithViewModel:ask];
//        MHMomentViewController *creamMoment = [[MHMomentViewController alloc] initWithViewModel:cream];
        [self setViewControllers:@[topicMoment]];
        self.headerHeight = MHRealHeightValue(200); // isIPhoneX() ? 200 :153;
        self.freezenHeaderWhenReachMaxHeaderHeight = YES;
        self.segmentMiniTopInset = 64;
//        if (@available(iOS 11.0, *)) {
//            self.segmentMiniTopInset = 84;
//        }
        [self addObserver:self forKeyPath:@"segmentTopInset" options:NSKeyValueObservingOptionNew context:NULL];
    }
    return self;
}

- (void)dealloc
{
    [self removeObserver:self forKeyPath:@"segmentTopInset"];
}




-(UIButton *)hoverBtn
{
    if (!_hoverBtn) {
        _hoverBtn = [UIButton new];
        [_hoverBtn setImage:MHImageNamed(@"icon_circle_hoverbtn") forState:0];
        [self.view addSubview:_hoverBtn];
        [_hoverBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.view).offset(-20);
//            make.bottom.equalTo(self.view).offset(-100);
            make.bottom.equalTo(self.view).multipliedBy(0.95);
            make.height.mas_equalTo(@64);
            make.width.mas_equalTo(@64);
        }];
    }
    return _hoverBtn;
}

- (void)_back{
    if (self.viewModel.fromeCreate) {
        [self.viewModel.services popToRootViewModelAnimated:YES];
    }else
    {
        [self.viewModel.services popViewModelAnimated:YES];
    }
    
    
}
-(UIView<ARSegmentPageControllerHeaderProtocol> *)customHeaderView
{
    if (_header == nil) {
        _header = [MHCircleInfoHeader mh_viewFromXib];
        _header.settingButton.rac_command = self.viewModel.nextCommand;
        _header.searchBtn.rac_command = self.viewModel.searchCommand;
        
        __weak __typeof(self)weakSelf = self;
        [_header.backButton bk_whenTapped:^{
            //            if (!self.navigationController.presentedViewController) {
            //                [weakSelf.viewModel.services popViewModelAnimated:YES];
            //            }else
            //            {
            //                [weakSelf.viewModel.services dissMissAllPresentModelAnimated:YES];
            //            }
            //
            [weakSelf.viewModel.services popToRootViewModelAnimated:YES]; //重新创建了
        }];
      
    }
    return _header;
}


-(void)bindViewModel
{
    [super bindViewModel];
    
    
}

-(void)viewWillAppear:(BOOL)animated
{
     self.inThisPage = YES;
    [super viewWillAppear:animated];
    self.isExpand = YES;
    [self willChangeValueForKey:@"segmentTopInset"];
    [self didChangeValueForKey:@"segmentTopInset"];
    @weakify(self);
    [[self.viewModel.fetchCircleInfoCommand execute:nil] subscribeNext:^(MHCircleInfo *circelInfo) {
        @strongify(self);
        [AXAppDelegate sharedDelegate].currentCircleInfo = circelInfo;
        self.activityButton.hidden = !circelInfo.isOpenActivity;
        self.viewModel.circleInfo.isOpenActivity = circelInfo.isOpenActivity;
        [self.activityButton.layer removeAllAnimations];
        [self.activityButton shake:CGFLOAT_MAX withDelta:30 speed:0.1 shakeDirection:ShakeDirectionRotation completion:nil];
    }];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isExpand    = YES;
    @weakify(self);
    self.activityButton.hidden = YES;
    if (!self.viewModel.circleInfo) {
        [[self.viewModel.fetchCircleInfoCommand execute:nil] subscribeNext:^(MHCircleInfo *circelInfo) {
            @strongify(self);
            [self configUiWith:circelInfo];
        }];
        
    }else
    {
        [self configUiWith:self.viewModel.circleInfo];
        [self showSuccessTipMessage];
    }
    [self configRinghtItemsWithExpand:YES];
    [self.hoverBtn addTarget:self action:@selector(hoverBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [RACObserve([AXAppDelegate sharedDelegate], uploadProgress) subscribeNext:^(NSNumber *num) {
        @strongify(self);
        
        if ([AXAppDelegate sharedDelegate].publushCircleInfo.autoId == self.viewModel.circleInfo.autoId) {
            self.header.progress.progressValue = [num floatValue];
            self.header.progress.contentText = [NSString stringWithFormat:@"%.0f%%",[num floatValue]*100 ];
            if(self.header.progress.progressValue <= 0 || self.header.progress.progressValue >=1)
            {
                self.header.progress.hidden = YES;
            }else
            {
                self.header.progress.hidden = NO;
            }
        }
    }];
    
    
    [self.header.locationBtn bk_whenTapped:^{
        if (self.viewModel.circleInfo.location) {
            MHDetailLocationViewModel *locationViewModel =  [[MHDetailLocationViewModel alloc] initWithServices:self.viewModel.services params:@{MHViewModelUtilKey:self.viewModel.circleInfo.location}];
            [self.viewModel.services pushViewModel:locationViewModel  animated:YES];
        }
    }];
    
    
    
}

-(void) hoverBtnClick:(UIButton *)btn
{
    SharePopView *popView = [[SharePopView alloc] initWithCircleInfo];
    __weak __typeof(self)weakSelf = self;
     __weak __typeof(popView) weakPopView = popView;
    popView.circleBottonCilckBlock = ^(int index) {
        [weakPopView dismiss];
        if (index == 0) {
            [[AXAppDelegate sharedDelegate] clearPublishDatas];
            [TXUGCBase setLicenceURL:@"http://license.vod2.myqcloud.com/license/v1/42003ce1c142554c34c267d6887d3437/TXUgcSDK.licence" key:@"9e00381d6a084de6980fae22a259b196"];
            [weakSelf.viewModel.bottomInfoViewModel.takeVideoCommand execute:nil];
        }else if (index == 1)
        {
            if ([AXAppDelegate sharedDelegate].currentCircleInfo.canPublish) {
                [self openCameraIsPublish:YES selectedAssets:nil completionBlock:^(NSArray *photos,NSArray *assert){
                    [weakSelf.viewModel.bottomInfoViewModel.pulishCommand execute:@{@"photos":photos,@"assert":assert}];
                }];
               
            }else
            {
                [MBProgressHUD mh_showTips:@"没有发表权限"];
            }
        }else
        {
                [weakSelf.viewModel.bottomInfoViewModel.askCommand execute:nil];

        }
    };
    [popView show];
}

-(UIButton *)activityButton
{
    if (!_activityButton) {
        _activityButton = [UIButton new];
        //        _activityButton.hidden = YES;
        [_activityButton setImage:MHImageNamed(@"circle_activity") forState:0];
        [self.view addSubview:_activityButton];
        [_activityButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(self.view).offset(-20);
            make.centerY.equalTo(self.view).multipliedBy(0.5);
            make.height.mas_equalTo(@55);
            make.width.mas_equalTo(@61);
        }];
        //        self.navigationController.navigationBar.translucent
        
    }
    return _activityButton;
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    if ([keyPath isEqualToString:@"segmentTopInset"] && self.inThisPage) {
        CGFloat topInset = [change[NSKeyValueChangeNewKey] floatValue];
        if (topInset <= self.segmentMiniTopInset) {
//            if (topInset == self.segmentMiniTopInset) {
            
//            }
//            self.header.ownerBtn.hidden = YES;
//            self.header.myAvaterImage.hidden = YES;
//            self.header.infoContainer.hidden = YES;
//            self.header.maskView.hidden = YES;
            self.header.hidden = YES;
            self.title =  self.viewModel.circleInfo.title;
            if (self.isExpand != NO) {
               self.isExpand = NO;
               [self configRinghtItemsWithExpand:NO];
               [self.navigationController.navigationBar setBackgroundImage:MHNavBackGround() forBarMetrics:UIBarMetricsDefault];
//                self.navigationController.navigationBar.translucent = NO;
            }
            
        }else{
            self.header.hidden = NO;
//            self.header.ownerBtn.hidden = NO;
//            self.header.myAvaterImage.hidden = NO;
//             self.header.infoContainer.hidden = NO;
//            self.header.maskView.hidden = NO;
            self.title = @"";
            if (self.isExpand != YES) {
                self.isExpand = YES;
                [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:[UIColor clearColor]] forBarMetrics:UIBarMetricsDefault];
                [self configRinghtItemsWithExpand:YES];
            }
            
        }
        
    }
    
    [self.header layoutSubviews];
    
}


- (void)setStatusBarBackgroundColor:(UIColor *)color {
    
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    NSLog(@"statusBar.backgroundColor--->%@",statusBar.backgroundColor);
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = color;
    }
}

-(void)viewWillDisappear:(BOOL)animated
{
    self.inThisPage = NO;
    self.isExpand = NO;
    [super viewWillDisappear:animated];
    //    [self setStatusBarBackgroundColor:[UIColor clearColor]];
    //    [self.navigationController.navigationBar setBackgroundImage:MHNavBackGround() forBarMetrics:UIBarMetricsDefault];
    //    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    //    self.navigationController.navigationBar.translucent = NO;
}

-(void)showSuccessTipMessage
{
    if ([AXAppDelegate sharedDelegate].isAuthorizationExpired) {
        
    }
}

-(void) configRinghtItemsWithExpand:(BOOL ) isExpand
{
    UIBarButtonItem *leftBarItem = [UIBarButtonItem mh_backItemWithTitle:nil imageName:isExpand ? @"icon_back":@"barbuttonicon_back_15x30" target:self action:@selector(_back)];
    // 4.这里可以设置导航栏的左右按钮 统一管理方法
    self.navigationItem.leftBarButtonItem = leftBarItem;
    
    UIBarButtonItem *searchItem =   [UIBarButtonItem mh_systemItemWithTitle:nil titleColor:nil imageName:isExpand ? @"circle_search":@"icon_search_black" target:nil selector:nil textType:NO];
    searchItem.rac_command = self.viewModel.searchCommand;
    UIBarButtonItem *settingItem =   [UIBarButtonItem mh_systemItemWithTitle:nil titleColor:nil imageName:isExpand ? @"circle_setting":@"icon_more_black" target:nil selector:nil textType:NO];
    settingItem.rac_command = self.viewModel.nextCommand;
    self.navigationItem.rightBarButtonItems = @[settingItem,searchItem];
}
-(void) configUiWith:(MHCircleInfo *)info
{
    [AXAppDelegate sharedDelegate].currentCircleInfo = info;
    self.viewModel.circleInfo = info;
    @weakify(self);
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.header.ownerBtn yy_setBackgroundImageWithURL:[NSURL URLWithString:info.fullOwnerFace] forState:UIControlStateNormal placeholder:MHDefaultAvatar(MHDefaultAvatarTypeDefualt)];
        if (MHCurretUserId() == info.ownerUid) {
            self.header.myAvaterImage.hidden = YES;
        }else
        {
            [self.header.myAvaterImage yy_setImageWithURL:[NSURL URLWithString:[MHHTTPService sharedInstance].currentUser.allHeadPath] placeholder:MHDefaultAvatar(MHDefaultAvatarTypeDefualt)];
        }
        
        [RACObserve(self.viewModel.circleInfo, fullCoverUrl) subscribeNext:^(NSString *coverUrl) {
            @strongify(self);
            __weak __typeof(self)weakSelf = self;
            [self.header.circleBgImageView yy_setImageWithURL:[NSURL URLWithString:coverUrl] placeholder:MHCircleBgPlaceHolder() options:nil completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
//                [image applyExtraLightEffect]
                weakSelf.header.circleBgImageView.image = image;//[self convertToBlurImage:image];
            }];
        }];
        self.header.payIcon.hidden = (info.payType != MHCirclPayTypeCharge);
        RAC(self.header.circleNameLable,text) = RACObserve(info, title);
        RAC(self.header.circleDescLabel,text) = RACObserve(info, intro);
        
        [RACObserve(self.viewModel.circleInfo, location) subscribeNext:^(MHCircleLocationModel *model) {
           @strongify(self);
            self.header.locationBtn.hidden = !model.isShowLocation;
            [self.header.locationBtn setTitle:[NSString stringWithFormat:@" %@",[info fetchShowLocation]] forState:0];
        }];
        
    });
    
    
    
    self.activityButton.hidden = !info.isOpenActivity;
    
    [self.activityButton shake:CGFLOAT_MAX withDelta:20 speed:0.1 shakeDirection:ShakeDirectionRotation completion:nil];
    [_activityButton bk_whenTapped:^{
        @strongify(self);
        if (info.isOpenActivity) {
            NSString *url = [NSString stringWithFormat:@"%@reward-project-create.html?circleId=%d",[MHConfigureManager h5BaseUrl],info.autoId];
            url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
            MHWebViewModel * webViewModel = [[MHWebViewModel alloc] initWithServices:self.viewModel.services params:@{MHViewModelRequestKey:request}];
            webViewModel.shouldDisableWebViewClose = YES;
            webViewModel.translucentNavigationBar = YES;
            webViewModel.showRightShareIcon = YES;
            webViewModel.prefersNavigationBarBottomLineHidden = YES;
            [self.viewModel.services pushViewModel:webViewModel animated:YES];
        }
    }];
    
}

-(UIImage *)convertToBlurImage:(UIImage *)image{
    CIFilter *gaussianBlurFilter = [CIFilter filterWithName:@"CIGaussianBlur"];
    [gaussianBlurFilter setDefaults];
    CIImage *inputImage = [CIImage imageWithCGImage:[image CGImage]];
    [gaussianBlurFilter setValue:inputImage forKey:kCIInputImageKey];
    [gaussianBlurFilter setValue:@1   forKey:kCIInputRadiusKey];
    CIImage *outputImage = [gaussianBlurFilter outputImage];
    CIContext *context   = [CIContext contextWithOptions:nil];
    CGImageRef cgimg     = [context createCGImage:outputImage fromRect:[inputImage extent]];  // note, use input image extent if you want it the same size, the output image extent is larger
    UIImage *convertedImage = [UIImage imageWithCGImage:cgimg];
    return convertedImage;
}



-(void)rightButtonClick
{
    [self.viewModel.nextCommand execute:nil];
}

//-(MHCircleMainPageBottonView *)circleInfoBottom
//{
//    if (!_circleInfoBottom) {
//        _circleInfoBottom = [MHCircleMainPageBottonView mh_viewFromXib];
//        __weak __typeof(self)weakSelf = self;
//        
//
//        [_circleInfoBottom.publishBtn bk_whenTapped:^{
//            if ([AXAppDelegate sharedDelegate].currentCircleInfo.canPublish) {
//
//                 [self openCameraIsPublick:NO completionBlock:^{
//                     [weakSelf.viewModel.bottomInfoViewModel.pulishCommand execute:nil];
//                 }];
//
//            }else
//            {
//                [MBProgressHUD mh_showTips:@"没有发表权限"];
//            }
//
//        }];
//
//        [_circleInfoBottom.takeVideoBtn bk_whenTapped:^{
//
//            [weakSelf.viewModel.bottomInfoViewModel.takeVideoCommand execute:nil];
//        }];
//
//
//
//
//        [_circleInfoBottom.answerBtn bk_whenTapped:^{
//            [self openCameraIsPublick:NO completionBlock:^{
//                [weakSelf.viewModel.bottomInfoViewModel.askCommand execute:nil];
//            }];
//
//        }];
//
//    }
//    return _circleInfoBottom;
//}


-(void)openCameraIsPublish:(BOOL) isPublish selectedAssets:(NSArray *)selecatedAssets completionBlock:(VoidBlock_id_id)completionBlock  {
    [MHPhotoManager fetchPhotosFromAlbum:self maxImagesCount:isPublish?9:1 allowCrop:NO selectedAssets:selecatedAssets completion:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto, NSArray<NSDictionary *> *infos) {
        NSMutableArray *photesArray =  [MHPhotoManager selectedAlbumPhotosIncludingGifWithPHAssets:assets photos:photos];
        completionBlock(photesArray,assets);
    } cancel:^{
        
    }];
}



@end
